package com.djhu.newscollector.crawel.imp.cl;

import com.djhu.newscollector.crawel.core.Url;
import com.djhu.newscollector.crawel.net.DefaultHttpVisitor;
import com.djhu.newscollector.crawel.net.HttpRequest;
import com.djhu.newscollector.crawel.net.HttpVisitor;
import com.djhu.newscollector.crawel.net.Page;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Commons {
    public static boolean downloadFile(String fileUrl, String fileLocal) throws Exception {
        FileOutputStream outputStream = null;
        if (fileUrl.startsWith("https")) {
            Url url = new Url();
            url.setUrl(fileUrl);
            HttpRequest request = new HttpRequest();
            request.setUrl(url);
            HttpVisitor httpVisitor = new DefaultHttpVisitor();

            Page page = httpVisitor.visit(request);
            byte[] bytes = page.content();
            try {
                if (bytes == null){
                    return false;
                }
                outputStream = new FileOutputStream(fileLocal);
                outputStream.write(bytes);
            } catch (Exception e) {
                e.printStackTrace();                 ;
                return false;
            } finally {
                IOUtils.closeQuietly(outputStream);
            }
            return true;
        } else {

            HttpURLConnection conn = (HttpURLConnection) new URL(fileUrl)
                    .openConnection();
            conn.setReadTimeout(Config.TIMEOUT_READ);
            conn.setConnectTimeout(Config.TIMEOUT_CONNECT);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36");
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                try {
                    outputStream = new FileOutputStream(fileLocal);
                    byte[] bytes = readInputStream(inputStream);
                    outputStream.write(bytes);
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                } finally {
                    IOUtils.closeQuietly(outputStream);
                }
            }


            return false;
        }

    }

    public static boolean downloadFile(String fileUrl, String fileLocal,int retry)  {
        for (int i = 0;i<retry;i++){
            try {
                boolean isSuccess = downloadFile(fileUrl,fileLocal);
                if (isSuccess){
                    return isSuccess;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }


    public static void main(String[] args) throws Exception {
        //https://www1.wi.to/2018/02/03/f48bafb08f68d4bcc4a1d3235479c16b.md.jpg
        String url = "http://www.srimg.com/u/20180210/08490064.jpg";
//        Config.MAX_RECEIVE_SIZE = Integer.MAX_VALUE;
//        HttpRequest request = new HttpRequest(url);
//       HttpResponse rsp = request.response();
//        byte[] code = rsp.content();
//        //rsp.
//        FileOutputStream fileWriter = new FileOutputStream("./1.jpg");
//        fileWriter.write(code);
//        fileWriter.close();;
        Commons.downloadFile(url, "./1.jpg");
        //System.out.println(code);
    }
}
